const qiniu = require('qiniu');

/**
 * @api {get} /api/public/v1/upload/params 获取上传参数
 */
exports.params = function ({query}, {config, qiniu}) {
    return qiniu.uploadParams(config.qiniu, query.type);
}

/**
 * @api {get} /api/public/v1/upload/ueditor ueditor图片上传
 */
exports.ueditor = function ({req, query}, {models: {Images}, config, qiniu}) {
    let {action, type, start, reference} = query, ueditor = config.ueditor;
    let ueConfig = ueditor && ueditor.data || {
            imageManagerActionName: "listimage",
            imageManagerListSize: 20,
            imageActionName: "uploadimage",
            imageFieldName: "upfile",
            imageMaxSize: 2048000,
            imageAllowFiles: [".png", ".jpg", ".jpeg", ".gif", ".bmp"]
        };
    ueConfig.imageUrlPrefix = config.qiniu.ue_domain;
    ueConfig.imageManagerUrlPrefix = '';

    switch (action) {
        case 'uploadimage':
            return qiniu.formUpload(req, config.qiniu, 'ue').then(function (result) {
                if (result.success) {
                    let file = result.file;
                    Images.create({type: type, reference: reference, image: file.url});
                    return {url: file.name, original: file.filename, state: 'SUCCESS'};
                } else {
                    return {state: 'FAILED'};
                }
            });
            break;
        case 'listimage':
            return Images.findAndCountAll({
                where: {type: type}, order: [['id', 'desc']], start: start,
                limit: ueConfig.imageManagerListSize,
                attributes: [['image', 'url']]
            }).then(function (data) {
                return {state: "SUCCESS", start: start, list: data.rows, total: data.total};
            });
            break;
        default:
            return ueConfig;
            break;
    }
}
